package com.example.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.aop.MyLog;
import com.example.entity.User;
import com.example.service.UserService;
import com.example.utils.randomData;
import com.example.utils.redis.RedisCache;
import com.example.utils.result.BaseCodeConstant;
import com.example.utils.result.BaseResponse;
import com.example.utils.security.Md5Utils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api("用户模块")
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    RedisTemplate<String, Serializable> redisTemplate;

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @RequestMapping("/importUsers")
    public String importExcel(HttpServletRequest request){
        String realPath = request.getSession().getServletContext().getRealPath("fileTemple");
        String result=userService.importUserList();
        return result;
    }

    @ApiOperation(value = "用户新增", notes = "新增单个用户")
    @RequestMapping(value = "/saveSingerUser", method = RequestMethod.POST)
    public BaseResponse saveSingerUser(HttpServletRequest request) {
        BaseResponse<Object> baseResponse = new BaseResponse<>(BaseCodeConstant.SYSTEM_ERROR, "System error");
        User user = new User();
        String name = randomData.getName();
        user.setId(randomData.uniqueValueId());
        user.setUsername(name);
        user.setPassword(Md5Utils.hash("123456"));
        user.setActName(name);
        user.setEmail(randomData.getEmail(16, 22));
        user.setPhone(randomData.getTel());
        user.setStatus('1');
        user.setRole('0');
        int result = 0;
        try {
            result = userService.insertUser(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result <= 0) {
            baseResponse.setResultCode(BaseCodeConstant.SYSTEM_ERROR);
            baseResponse.setResultMessage("未知异常");
            baseResponse.setResult(result);
            return baseResponse;
        }
        baseResponse.setResultCode(BaseCodeConstant.SUCCESS);
        baseResponse.setResultMessage("success");
        baseResponse.setResult(result);
        return baseResponse;
    }


    @ApiOperation(value = "查询单个用户", notes = "查询单个用户")
    @RequestMapping(value = "/queryUserById", method = RequestMethod.POST)
    public BaseResponse queryUserById(@RequestBody Map<String, Object> map) {
        BaseResponse<Object> baseResponse = new BaseResponse<>(BaseCodeConstant.SYSTEM_ERROR, "System error");
        String id=(String) map.get("id");
        //使用redis缓存预先读取查询缓存,id为key,用户信息为 value
        User user = redisCache.getCacheObject(id);
        if (user == null) {
            user = userService.selectUserById(id);
            redisCache.setCacheObject(id, user, 10, TimeUnit.SECONDS);
        }
        baseResponse.setResultCode(BaseCodeConstant.SUCCESS);
        baseResponse.setResultMessage("success");
        baseResponse.setResult(user);
        return baseResponse;
    }

    @ApiOperation(value = "条件查询", notes = "条件查询")
    @RequestMapping(value = "/queryUserByParams", method = RequestMethod.POST)
    public BaseResponse queryUserByParams(@RequestBody Map<String, Object> map) {
        BaseResponse<Object> baseResponse = new BaseResponse<>(BaseCodeConstant.SYSTEM_ERROR, "System error");
        //使用redis缓存预先读取查询缓存
        List<User> userList = redisCache.getCacheObject("users");
        if (userList == null) {
            userList = userService.selectUserByParams(map);
//            redisCache.setCacheObject("user",user);
            redisCache.setCacheObject("users", userList, 10, TimeUnit.SECONDS);
        }
        baseResponse.setResultCode(BaseCodeConstant.SUCCESS);
        baseResponse.setResultMessage("success");
        baseResponse.setResult(userList);
        return baseResponse;
    }

    @RequestMapping(value = "/queryUserByPage", method = RequestMethod.POST)
    public BaseResponse queryUserByPage(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        BaseResponse<Object> baseResponse = new BaseResponse<>(BaseCodeConstant.SYSTEM_ERROR, "System error");
        //使用redis缓存预先读取查询缓存
//        List<User> userList = redisCache.getCacheList("userList");
//        int pageNo = (int) params.get("pageNo");
//        int pageSize = (int) params.get("pageSize");
//        if (userList == null || userList.size() == 0) {
//            int startIndex = (pageNo - 1) * pageSize;
//            params.put("startIndex", startIndex);
//            userList = userService.queryUserByList(params);
////            redisCache.setCacheObject("userList",userList,30, TimeUnit.SECONDS);
//            redisCache.setCacheList("userList", userList);
//            redisCache.expire("userList", 30, TimeUnit.SECONDS);
//        }
        int pageNo = (int) params.get("pageNo");
        int pageSize = (int) params.get("pageSize");
        int startIndex = (pageNo - 1) * pageSize;
        params.put("startIndex", startIndex);
        List<User> userList = userService.queryUserByPage(params);
        baseResponse.setResultCode(BaseCodeConstant.SUCCESS);
        baseResponse.setResultMessage("success");
        baseResponse.setResult(userList);
        return baseResponse;
    }

    @ApiOperation(value = "批量新增用户", notes = "批量新增用户")
    @RequestMapping(value = "/batchSaveUsers", method = RequestMethod.POST)
    public BaseResponse batchInsertUser(@RequestBody String json, HttpServletRequest request) {
        BaseResponse<Object> baseResponse = new BaseResponse<>(BaseCodeConstant.SYSTEM_ERROR, "System error");
        JSONObject params = JSONObject.parseObject(json);
        int param = (int) params.get("params");
        int result = 0;
        try {
            result = userService.batchInsertUser(param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (result == 0) {
            baseResponse.setResultCode(BaseCodeConstant.SYSTEM_ERROR);
            baseResponse.setResultMessage("未知异常");
            baseResponse.setResult(result);
            return baseResponse;
        }
        baseResponse.setResultCode(BaseCodeConstant.SUCCESS);
        baseResponse.setResultMessage("success");
        baseResponse.setResult(result);
        return baseResponse;
    }

    //用户登录
    @RequestMapping("login")
    public Object login(HttpServletRequest request) {
        //将已经登录的用户信息添加到session中
        request.getSession().setAttribute("user","{username:zhangsan,age:123}");
        return "Login Success";
    }

    //如果用户未登录访问了需要登录才能访问的请求会跳转到这个错误提示页面
    @RequestMapping("/error")
    public Object error() {
        return "You Must Login";
    }
}
